package org.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 卖票问题
 */
public class SaleTicketDemo2 {

    public static void main(String[] args) {
        ticket ticket = new ticket();

        new Thread(()-> {for (int i = 0; i < 40; i++)ticket.sale();},"A").start();
        new Thread(()->{for (int i = 0; i < 40; i++)ticket.sale();},"B").start();
        new Thread(()->{for (int i = 0; i < 40; i++)ticket.sale();},"C").start();


//        System.out.println(ticket.num);
    }


    static class ticket{
        private Integer num = 50;


        Lock lock = new ReentrantLock();



        public void sale(){
            lock.lock();  // 加锁
            try {
                if(num > 0){
                    System.out.println("买到是的第"+num--+"张票,剩余多少张"+num);
                }
            }catch (Exception e){

            }finally {
                lock.unlock(); // 解锁
            }
        }
    }
}
